﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Input;
using Core;
using Core.Interfaces;
using Core.Settings;
using DataXml;
using DataXml.CommunityFiles;
using Microsoft.Win32;

namespace TallyJ.Windows
{
  /// <summary>
  /// Interaction logic for DbTools.xaml
  /// </summary>
  public partial class DbTools
  {
    ///<summary></summary>
    public static RoutedCommand FindXmlCommand = new RoutedCommand();

    private Community _community;

    private IEnvironment _currentEnvironment;

    ///<summary></summary>
    public DbTools() : this(null)
    {
    }

    ///<summary></summary>
    public DbTools(IEnvironment environment)
    {
      InitializeComponent();
      _currentEnvironment = environment;

      CommandBindings.Add(new CommandBinding(FindXmlCommand, FindXml, (sender, args) => args.CanExecute = true));

      btnFind.Command = FindXmlCommand;

      KeyDown += OnKeyDown;

      CommunityFilePath.Text = _currentEnvironment.Settings.SourceXmlCommunityFilePath;
    }

    private void FindXml(object sender, ExecutedRoutedEventArgs e)
    {
      var fileDialog = new OpenFileDialog
                         {
                               CheckFileExists = true,
                               CheckPathExists = true,
                               DefaultExt = ".xml",
                               Title = "Select existing Community XML file",
                               FileName = _currentEnvironment.Settings.SourceXmlCommunityFilePath,
                               Multiselect = false,
                               InitialDirectory =
                                     Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                  "TallyJ"),
                               ValidateNames = true,
                               DereferenceLinks = true,
                               AddExtension = true,
                               Filter = "TallyJ 1.x Community File (.xml)|*.xml"
                         };
      var okay = fileDialog.ShowDialog();
      if (okay.Value)
      {
        var newPath = fileDialog.FileName;
        TestAndSaveCommunityFilePath(newPath);
        CommunityFilePath.Text = _currentEnvironment.Settings.SourceXmlCommunityFilePath;
      }
    }


    private void OnKeyDown(object sender, KeyEventArgs args)
    {
      switch (args.Key)
      {
        case Key.Escape:
          Close();
          break;
      }
    }

    

    private void CommunityFilePath_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
      var newPath = CommunityFilePath.Text;

      try
      {
        if(!TestAndSaveCommunityFilePath(newPath))
        {
          CommunityFilePath.Text = _currentEnvironment.Settings.SourceXmlCommunityFilePath;
          FileStatusLabel.Content = "File valid";
        }
      }
      catch (Exception exception)
      {
        CommunityFilePath.Text = string.Empty;
        FileStatusLabel.Content = "File not valid";
      }
    }

    private bool TestAndSaveCommunityFilePath(string newPath)
    {
      if (File.Exists(newPath))
      {
        //var importer = IoC.Container.Resolve<ICommunityImporter>();
        var importer = new CommunityImporter();
        importer.ImportCommunity(newPath);

        if (importer.Successful)
        {
          _currentEnvironment.Settings.SourceXmlCommunityFilePath = newPath;
          _currentEnvironment.Community = importer.Community;
          return true;
        }
        
        MessageBox.Show(importer.ErrorMessages.JoinedAsString("\n"), "Error");
      
      }
      else
      {
        MessageBox.Show("File not found.");
      }

      return false;
    }
  }
}